package com.neusoft.elmboot.controller;

import com.neusoft.elmboot.po.Food;
import com.neusoft.elmboot.service.FoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import jakarta.servlet.http.Cookie;
import java.util.Map;
import java.util.List;

@RestController
@RequestMapping("/api/foods")
public class FoodController {

    @Autowired
    private FoodService foodService;

    @GetMapping("/list")
    public List<Food> listFoodByBusinessId(@RequestParam Integer businessId) throws Exception {
        return foodService.listFoodByBusinessId(businessId);
    }

    @DeleteMapping("/{foodId}")
    public ResponseEntity<?> removeFood(@PathVariable Integer foodId,
                                        @CookieValue(value = "token", required = false) String token,
                                        @RequestParam String userId) {
        if (token == null || !token.equals(userId)) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("权限不足");
        }
        int result = foodService.removeFood(foodId);
        return result > 0 ? ResponseEntity.ok(Map.of("affectedRows", result))
                          : ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("删除失败");
    }

    @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<String> addFood(@RequestParam("foodName") String foodName,
                                          @RequestParam("foodExplain") String foodExplain,
                                          @RequestParam(value = "foodImg", required = false) MultipartFile foodImg,
                                          @RequestParam("foodPrice") Double foodPrice,
                                          @RequestParam("businessId") Integer businessId,
                                          @RequestParam("userId") String userId) {
        try {
            Food food = new Food();
            food.setFoodName(foodName);
            food.setFoodExplain(foodExplain);
            food.setFoodPrice(foodPrice);
            food.setBusinessId(businessId);

            if (foodImg != null && !foodImg.isEmpty()) {
                String imgPath = "/www/wwwroot/http/image/" + System.currentTimeMillis() + "_" + foodImg.getOriginalFilename();
                java.nio.file.Files.write(java.nio.file.Paths.get(imgPath), foodImg.getBytes());
                food.setFoodImg(imgPath);
            } else {
                food.setFoodImg(null);
            }

            int result = foodService.addFood(food);
            return result > 0 ? ResponseEntity.ok("新增食品成功！")
                              : ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("新增食品失败！");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器内部错误：" + e.getMessage());
        }
    }

    @PatchMapping("/price")
    public ResponseEntity<String> updateFoodPrice(@RequestBody Food food) {
        try {
            int result = foodService.updateFoodPrice(food);
            return result > 0 ? ResponseEntity.ok("商品价格更新成功")
                              : ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("更新失败，找不到对应的商品");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器内部错误：" + e.getMessage());
        }
    }
}